package com.github.freewu.commons.libs;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.github.freewu.commons.utils.ToastUtil;
import com.lqkj.commons.R;

/**
 * Created by free on 16-9-6.
 */
public class SimpleWebView extends LinearLayout implements View.OnClickListener,DownloadListener{

    public static final String URL = "url";

    public static final String TITLE="title";

    private ProgressBar progressBar;

    private WebView webView;

    private RelativeLayout relaReload;

    private String url;

    public SimpleWebView(Context context) {
        super(context);

        init();
    }

    public SimpleWebView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public SimpleWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }
    private void init(){
        LayoutInflater.from(getContext()).inflate(R.layout.simplpe_web_view,this);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        webView = (WebView) findViewById(R.id.webView);

        relaReload=(RelativeLayout)findViewById(R.id.rela_reload);
        relaReload.setOnClickListener(this);

        WebSettings webSettings= webView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setDatabaseEnabled(true);

        //设置定位的数据库路径
        String dir = this.getContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setGeolocationDatabasePath(dir);

        //启用地理定位
        webSettings.setGeolocationEnabled(true);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        //下载文件
        webView.setDownloadListener(this);

        webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                SimpleWebView.this.url=url;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
                    if (error.getErrorCode()==-2) {
                        relaReload.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);

                if (Build.VERSION.SDK_INT<Build.VERSION_CODES.M) {
                    relaReload.setVisibility(View.VISIBLE);
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (progressBar.getVisibility() == View.GONE)
                        progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin,true,false);

                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });
    }

    public String getUrl() {
        return url;
    }

    public synchronized void setUrl(String url) {
        this.url = url;

        webView.loadUrl(url);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();

        if (i == R.id.rela_reload) {
            webView.loadUrl(url);

            relaReload.setVisibility(View.GONE);
        }
    }

    public WebView getWebView() {
        return webView;
    }

    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
        ToastUtil.showShort(getContext(),"正在下载...");

        DownloadManager downloadManager= (DownloadManager)getContext().getSystemService(Context.DOWNLOAD_SERVICE);

        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        downloadManager.enqueue(request);
    }
}
